package com.kgc.search.service.listener;

import com.kgc.dao.TbItemMapper;
import com.kgc.utils.SearchItem;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

//监控mq ,从mq中得到新增加商品编号  itemId
//将新增加的商品增加solr库中
public class ActiveMqMessageListener implements MessageListener {

    @Autowired
    private TbItemMapper tbItemMapper;

    @Autowired
    private HttpSolrServer httpSolrServer;

    //1.根据itemIds查询到这个新商品  SearchItem

    //2.将这个新商品增加到solr中   Documenet

    @Override
    public void onMessage(Message message) {
        TextMessage textMessage=(TextMessage)message;
        Long itemId=null;
        SearchItem searchItem=null;
        try {
            //得到新增加商器编号
            Thread.sleep(1000);
            itemId=Long.parseLong(textMessage.getText());
            System.out.println("itemId:"+itemId);
            searchItem=tbItemMapper.searchItemById(itemId);
            addSearchItemToSolr(searchItem);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addSearchItemToSolr(SearchItem item) throws Exception{
        SolrInputDocument solrDocument = new SolrInputDocument();
        solrDocument.addField("id",item.getId());
        solrDocument.addField("item_title",item.getTitle());
        solrDocument.addField("item_sell_point", item.getSellPoint());
        solrDocument.addField("item_price", item.getPrice());
        solrDocument.addField("item_category_name", item.getCategoryName());
        solrDocument.addField("item_image",item.getImage());
        httpSolrServer.add(solrDocument);
        httpSolrServer.commit();
    }
}
